import { reqGetUserDetailById, reqGetUserInfo, reqLogin } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
    },
    // 设置vuex数据
    setUserInfo(state, data) {
      state.userInfo = data
    },
    // 删除token
    removeToken(state) {
      state.token = ''
      removeToken()
    },
    // 删除数据
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async login(context, data) {
      const res = await reqLogin(data)
      console.log(res)
      setToken(res.data)
      context.commit('setToken', res.data)
    },
    // 获取用户信息
    async getUserInfo(context) {
      const { data: data1 } = await reqGetUserInfo()
      // console.log(data)
      /**
     * 1. 发送请求 拿到员工基本信息
     * 2. 合并两个对象
     */
      const { data: data2 } = await reqGetUserDetailById(data1.userId)
      const res = { ...data1, ...data2 }
      context.commit('setUserInfo', res)
      return res
    },
    logout({ commit }) {
      commit('removeToken')
      commit('removeUserInfo')
    }
  }
}
